#!/usr/bin/php
<?

// Mates! - Background processing
// Authors:
//   Ayush Agarwal <yush@umich.edu>
//   Adam Herscher <ahersche@umich.edu>
//   Jeff Powers <jrpowers@umich.edu>

// path to mates htdocs
$MATES_PATH = "/home/mates/htdocs/mates0.4";

require_once("$MATES_PATH/config.php");
require_once("$MATES_PATH/libmates.php");

$timeout = $GLOBALS['IDLE_TIMEOUT'] * 60;

if (!db_connect()) // connect to the database
  die("Unable to connect to database.");

while (true) {
  $query = "select user_id, session_id, username from users where NOW() - lastreq_ts > $timeout";
  $res = mysql_query($query);
  if (!$res)
    return die(db_err($query));
  while ($row = mysql_fetch_row($res)) {
    $user_id = $row[0];
    $session_id = $row[1];
    $username = $row[2];
    
    // delete session_id
    $query2 = "update users set session_id = '' where user_id = '$user_id'";
    $res2 = mysql_query($query2);
    if (!$res2)
      die(db_err($query2));
    
    // we don't use getloc() here, because it's okay if user is not in a location
    $query2 = "select loc_id from in_loc where user_id = '$user_id'";
    $res2 = mysql_query($query2);
    if (!$res2)
      die(db_err($query2));
  
    if (mysql_num_rows($res2)) { // user has set a location
      $row2 = mysql_fetch_object($res2);
      $loc_id = $row2->loc_id;

      list($p1, $p2) = exit_loc($user_id, $loc_id, $session_id, $username, 1);
      if (!$p1)
        die($p2);
    }
    
  }
  
  sleep($GLOBALS['BG_SLEEP']);
}
?>